package swing.customComp;

import client.UserSession;
import swing.FrameManager;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MemberListMouseListener extends MouseAdapter {
    JList memberList;
    JPopupMenu memberMenu;
    JPopupMenu refreshMenu;


    public MemberListMouseListener(JList list, JPopupMenu menu){
        memberList = list;
        memberMenu = menu;

        refreshMenu = new JPopupMenu();
        JMenuItem refreshWhiteboard = new JMenuItem("刷新成员列表");
        refreshWhiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FrameManager.mainFrame.clearMemberSelection();
                FrameManager.mainFrame.updateMemberList();
            }
        });
        refreshMenu.add(refreshWhiteboard);
    }

    @Override
    public void mouseDragged(MouseEvent e){
        if (memberList.locationToIndex(e.getPoint()) == -1)
            memberList.clearSelection();

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // list.locationToIndex(e.getPoint()) 获取被点击的元素index
        // 左键 1   中 2   右键3
        int index = memberList.locationToIndex(e.getPoint());

        if (index == -1) {
            memberList.clearSelection();
            if (e.getButton() == 3){
                refreshMenu.show(memberList, e.getX(), e.getY());
            }
            return;
        }

        memberList.setSelectedIndex(index);
        UserSession.setSelectedMemberIndex(memberList.getSelectedIndex());

        if (UserSession.user.getId() != UserSession.getSelectedGroup().getAdmin_id()) {
            if (e.getButton() == 3)
                refreshMenu.show(memberList, e.getX(), e.getY());
            return;
        }

        if (e.getButton() == 3){
            if (UserSession.user.getId() == UserSession.getSelectedMember().getId())
                refreshMenu.show(memberList, e.getX(), e.getY());
            else
                memberMenu.show(memberList, e.getX(), e.getY());
        }
    }
}
